package com.turntochild.i09;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.eternity.classes.ATRP;
import com.eternity.classes.ATRP.Callback;
import com.innofidei.tools.InnofideiTools;
import com.turntochild.i09.ITurnToChildAppService.Stub;
import com.wondertek.mist.MistActivity;
import com.wondertek.mist.Utils;
import com.wondertek.mist.utils.StringUtils;

public class TurnToChildService extends Service {
	
	private static final int CHECK_START=0;
	private static final int CHECK_ERROR=1;
	private static final int CHECK_FAILURE=2;
	private static final int CHECK_SUCCESS=3;
	


	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CHECK_SUCCESS:
				Toast.makeText(TurnToChildService.this,"验证成功", Toast.LENGTH_SHORT).show();
//				Utils.sendMamLog(TurnToChildService.this, "true");
				toMistActivity((JSONObject)msg.obj);
				break;

			case CHECK_START:
				Toast.makeText(TurnToChildService.this,"请稍等，正在验证数据...", Toast.LENGTH_SHORT).show();
				break;
			case CHECK_ERROR:
				Toast.makeText(TurnToChildService.this,"连接服务器失败", Toast.LENGTH_SHORT).show();
				break;
				

			case CHECK_FAILURE:
				JSONObject error=(JSONObject)msg.obj;
				
				try {
					Toast.makeText(TurnToChildService.this,error==null?"数据异常":error.getString("error"), Toast.LENGTH_SHORT).show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				Utils.sendMamLog(TurnToChildService.this, "false");
				break;


			default:
				break;
			}
		}
		
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		return new TurnToChildBinder();
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	public class TurnToChildBinder extends Stub {

		@Override
		public void turnToChildApps(String encryptCode) throws RemoteException {
			try {
				checkIsTrue( encryptCode);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	
	
	private void checkIsTrue(final String encryptCode) throws Exception {
		
		String codeString = InnofideiTools.decrypt(encryptCode,"CpicAppstore");
		JSONTokener jsonParser = new JSONTokener(codeString);
		final JSONObject param = ((JSONObject) jsonParser.nextValue()) .getJSONObject("params");
		param.put("sxUserId", param.getString("userid"));
		//Log.i("TURNTOCHILD", param.toString());
		
		String checkUrl = Utils.getMetaValue(this, "mam.checkUrl");
		
		//Log.i("url", checkUrl);
		if(StringUtils.isBlank(checkUrl)){
			toMistActivity(param);
		} else {
			ATRP.request(checkUrl, null, param, new Callback() {

				public void onStart() {
					Message message = new Message();
					message.what = CHECK_START;
					handler.sendMessage(message);

				}

				public void onFailure(String msg) {
					Message message = new Message();
					message.what = CHECK_ERROR;
					handler.sendMessage(message);
				}

				@Override
				public void onSuccess(JSONObject result, Header[] headers) {

					boolean success = false;
					if (result == null) {
						success = false;
					} else {
						try {
							success = result.getBoolean("success");
						} catch (JSONException e) {
						}
					}
					if (success) {
						Utils.saveString(TurnToChildService.this,"mam.encryptCode", encryptCode);
						Message message = new Message();
						message.what = CHECK_SUCCESS;

						message.obj = param;
						handler.sendMessage(message);
					} else {
						Message message = new Message();
						message.what = CHECK_FAILURE;
						message.obj = result;
						handler.sendMessage(message);
					}

				}

			});
		}
	}

	private void toMistActivity(JSONObject param) {
	
		Intent intent = new Intent();
		intent.setAction(Utils.ACTION_MAM);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(this, MistActivity.class);
		intent.putExtra("param", param.toString());
		
		Utils.saveString(this.getApplicationContext(), "param", param.toString());
		this.startActivity(intent);
	}
}
